#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 
# md5findex.py
#
# Copyright (c) 2008, Andrey Usov <uandrey@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the <organization> nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

__version = "0.1"

import os, sys, md5flib

    
def update_index_data(directory, findex_data):
    """
    update index data
    - directory: directory for *.files
    - findex_data: filename of md5data index file
    """
    print "Directory: %s" % directory
    print "Index_data: %s\n" % findex_data
    
    # load md5data index from file
    index_data = md5flib.load_index_data(findex_data)
    # scan directory for *.files
    for filename in md5flib.scan_directory(directory):
        print "* %s" % filename
        md5data = md5flib.load_md5data(directory + "/" + filename)

        selected_index_data = md5flib.select_index_data(index_data, filename)
        print "\tmd5data/index_data: %d/%d" % (len(md5data), len(selected_index_data))
        # new data, not in index_data
        new_data = set(md5data) - set(selected_index_data)
        # old data, not actual, exists in index_data but not in real
        old_data = set(selected_index_data) - set(md5data)
        print "\tnew_data/old_data: %d/%d" % (len(new_data), len(old_data))
        
        # delete not existing data in index_data
        for data_item in old_data:
            if filename in index_data[data_item].split(","):
                data_item_filenames = index_data[data_item].replace(filename + ",", "")
                if data_item_filenames == '': 
                    del(index_data[data_item])
                else:
                    index_data[data_item] = data_item_filenames
        # add new data to index_data
        for data_item in new_data:
            try:
                if filename not in index_data[data_item].split(","):
                    index_data[data_item] += filename + ","
            except KeyError:
                index_data[data_item] = filename + ","
        
    # save index data   
    md5flib.save_index_data(findex_data, index_data)

if __name__ == "__main__":
    from optparse import OptionParser
    
    parser = OptionParser(version="%prog, v." + __version)
    parser.add_option("-d", "--directory", dest="directory", help="directory of md5data files")
    parser.add_option("-i", "--index", dest="index_data", help="index data of md5data files")
    (options, args) = parser.parse_args()
    
    if (options.directory == None) or (options.index_data == None):
        parser.error("Incorrect number of arguments, \n\nuse -h or --help for detail")
    else:
        update_index_data(options.directory, options.index_data)
